package com.smile.cloud.aopConfig.filter;

import ch.qos.logback.classic.helpers.MDCInsertingServletFilter;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.smile.cloud.common.base.constant.CommonConstant;
import com.smile.cloud.common.base.util.AbstractMyThreadContext;
import org.slf4j.MDC;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * 日志追踪过滤器
 *
 * @author LGC
 */
public class LogTraceRequestFilter extends MDCInsertingServletFilter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest)) {
            return;
        }
        //如前端传递了唯一标识ID 拿出来直接用 根据业务这段也可以删除 然后去掉if判断
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String traceId = servletRequest.getHeader(CommonConstant.TRACE_ID_HEADER);
        if (StrUtil.isEmpty(traceId)) {
            traceId = IdUtil.fastSimpleUUID();
        }
        AbstractMyThreadContext.setTraceId(traceId);
        MDC.put(CommonConstant.LOG_TRACE_ID, traceId);
        try {
            //从新调动父类的doFilter方法
            super.doFilter(request, response, chain);
        } finally {
            //资源回收
            MDC.remove(CommonConstant.LOG_TRACE_ID);
            AbstractMyThreadContext.removeTraceId();
        }
    }
}
